package com.juneng.utils;

import cn.hutool.json.JSONUtil;
import com.juneng.config.RedisUtil;
import com.juneng.constant.Constant;
import com.juneng.constant.RedisKey;
import com.juneng.exception.AuthException;
import com.juneng.vo.UserVo;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description:
 * @author: 吴昊
 * @date: 2019/11/28
 */
public class ServletUtils {
    /**
     * 获取request
     */
    public static HttpServletRequest getRequest() {
        return getRequestAttributes().getRequest();
    }

    public static String getUserId() {
        return getHeader(Constant.HTTP_HEADER_USER);
    }

    public static String getToken() {
        return getHeader(Constant.HTTP_HEADER_TOKEN);
    }

    public static ServletRequestAttributes getRequestAttributes() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return (ServletRequestAttributes) attributes;
    }
    public static UserVo getUser() {
        try {
            String userJson = SpringUtils.getBean(RedisUtil.class).get(RedisKey.USER_TOKEN  + "pc" +ServletUtils.getUserId()).toString();
            UserVo user = JSONUtil.toBean(userJson,UserVo.class);
            if (user == null) {
                throw new AuthException();
            }
            return user;
        }catch (Exception e) {
            throw new AuthException();
        }
    }
    /**
     * 获取请求头里的值
     */
    public static String getHeader(String name) {
        return getRequest().getHeader(name);
    }

}
